/**
 * 
 */
package com.googlecode.bestpaper.output.pdf.book;

import java.io.File;
import java.io.FileOutputStream;

import com.googlecode.bestpaper.syntax.BPMarkup;
import com.googlecode.bestpaper.syntax.book.BPBook;
import com.googlecode.bestpaper.utils.BestpaperUtils;
import com.lowagie.text.Document;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfWriter;

/**
 * @author xalinx at gmail dot com
 * @date Dec 29, 2009
 */
public class PDFBook extends BPBook<File, Document> {

	public PDFBook() {

	}

	private int chapterNumber = 0;

	@Override
	public <E extends BPMarkup> void addChild(E child) {
		PDFChapter chapter = (PDFChapter) child;
		chapter.setChapterNumber(++chapterNumber);
		super.addChild(child);
	}

	@Override
	protected Document buildSelf(File file, int fontStyle) throws Exception {
		float marginLeft = 50, marginRight = 50, marginTop = 50, marginBottom = 50f;
		Document document = new Document(PageSize.A4, marginLeft, marginRight,
				marginTop, marginBottom);
		BestpaperUtils.setDocument(document);
		BestpaperUtils.setMargin(marginLeft, marginRight, marginTop,
				marginBottom);
		PdfWriter.getInstance(document, new FileOutputStream(file));
		HeaderFooter footer = new HeaderFooter(new Phrase(), true);
		footer.setBorder(Rectangle.NO_BORDER);
		footer.setAlignment(HeaderFooter.ALIGN_RIGHT);
		document.setHeader(footer);
		document.open();
		return document;
	}

	@Override
	protected void finishBuild(File writer, Document document) {
		document.close();
	}

}
